package cn.hzc.fortess.core.filter;

import ch.qos.logback.core.util.StringCollectionUtil;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

//@Slf4j
public class XssFilter implements Filter {

    FilterConfig filterConfig = null;
    private List<String> urlExclusion = null;

    public XssFilter() {
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String servletPath = httpServletRequest.getServletPath();
        //log.debug("xss filter...{}",servletPath);
        if ((!CollectionUtils.isEmpty(this.urlExclusion)) && matchExclusion(servletPath)) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
        }

    }

    private boolean matchExclusion(String servletPath) {
        for (String url : this.urlExclusion) {
            if (servletPath.startsWith(url)) {
                return true;
            }
        }
        return false;
    }

    public List<String> getUrlExclusion() {
        return this.urlExclusion;
    }

    public void setUrlExclusion(List<String> urlExclusion) {
        this.urlExclusion = urlExclusion;
    }
}
